import React from 'react'
import { Form, Input, Button, message } from 'antd'
import { userLogin } from '@a/user'
import { useDispatch } from 'react-redux'
import { userLogin as _userLogin, filterMenu } from '@/store/slices/user' 
import { useNavigate } from 'react-router-dom'
export default function Login() {
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const doLogin = (params:any) => {
    
    userLogin(params).then(res => {
      if(res.data.code === 200){
        const { role, token, userInfo } = res.data.data;
        localStorage.setItem('role', role);
        localStorage.setItem('token', token);
        localStorage.setItem('userInfo', JSON.stringify(userInfo));
        // dispatch action 存储到redux中
        dispatch(_userLogin({role, token,userInfo }))
        dispatch(filterMenu())
        message.success('登录成功', 2, () => {
          // 去首页 
          navigate('/dashBoard', {replace: true})
        })
      }
      
    })
  }
  return (
    <div style={{maxWidth:800, margin: '20px auto'}}>
      <Form 
        labelCol={{ span: 8 }} 
        onFinish={doLogin}
        wrapperCol={{ span: 16 }}>
        <Form.Item label="用户名" name="userName" rules={[
          { required: true, message: '用户名必填' },
          {
            pattern: /^\w{4,8}$/
          }
        ]}>
          <Input placeholder='请输入用户名' />
        </Form.Item>
        <Form.Item label="密码" name="pwd" rules={[
          { required: true, message: '密码必填' },
          {
            pattern: /^\w{4,8}$/
          }
        ]}>
          <Input placeholder='请输入用户名' />
        </Form.Item>
        <Form.Item wrapperCol={{span: 16, offset: 8}}>
          <Button type='primary' htmlType='submit'>登录</Button>
        </Form.Item>
      </Form>
    </div>
  )
}
